import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';

/// 图片预览组件
class ImageViewWidget extends StatefulWidget {
  /// 图片点击路径
  final String src;

  const ImageViewWidget({
    super.key,
    required this.src,
  });

  @override
  State<StatefulWidget> createState() => _ImageViewWidgetState();
}

class _ImageViewWidgetState extends State<ImageViewWidget> {
  late BuildContext _context;

  /// 图片浮动显示组件
  OverlayEntry? _photoEntry;

  @override
  Widget build(BuildContext context) {

    _context = context;
    return GestureDetector(
      onTap: _onTapFunDj,
      child: Image.network(widget.src),
    );
  }

  /// 图片点击方法
  _onTapFunDj() {
    _createPhotoEntry();
  }

  /// 创建图片预览浮动显示组件
  void _createPhotoEntry() {
    _photoEntry ??= OverlayEntry(builder: (context) {
      return Positioned.fill(
        child: _photoItem(),
      );
    });
    // 往Overlay中插入插入OverlayEntry
    Overlay.of(_context).insert(_photoEntry!);
  }

  /// 关闭浮动方法
  _closePhotoEntry() {
    _photoEntry!.remove();
  }

  /// 预览组件
  _photoItem() {
    return PhotoView(
      imageProvider: NetworkImage(widget.src),
      onTapUp: (
        BuildContext context,
        TapUpDetails details,
        PhotoViewControllerValue controllerValue,
      ) {
        // 关闭方法
        _closePhotoEntry();
      },
    );
  }
}
